﻿using System;
using System.Threading.Tasks;
using Zhaoxi.Communication.Modbus;

namespace Zhaoxi.Communimcation.Test
{
    class Program
    {
        static void Main(string[] args)
        {
            // 上位机调用 


            ModbusBase modbus = new ModbusRTU("COM1", 9600, System.IO.Ports.Parity.None, 8, System.IO.Ports.StopBits.One);//9600波特率 无检验 8位数据位 停止位1
            //ModbusBase modbus = new ModbusAscii("COM1", 9600, System.IO.Ports.Parity.None, 8, System.IO.Ports.StopBits.One);
            //ModbusBase modbus = new ModbusTcp("127.0.0.1", 502);
            modbus.ReadTimeout = 500;
            modbus.EndianType = EndianType.ABCD;// 从站保持一致

            try
            {
                modbus.Open();
            }
            catch (Exception)
            {
                modbus.Close();
                throw;
            }
            //

            // 读  01 02 03 04
            // 写  05 06 15 16

            //var resultValues = modbusRTU.ReadKeepRegister(1, 3, 0, 5);
            //var resultValues = modbusRTU.ReadKeepRegisterFloat(1, 3, 0, 2);
            var result = modbus.Read<ushort>(1, 3, 0, 4);//主机地址 功能码 起始地址 4个寄存器
            //var result = modbus.Read<bool>(1, 1, 0, 20);
            if (result.Result.Code == 0)
            {
                result.Result.Datas.ForEach(v => Console.WriteLine(v));
            }
            else
                Console.WriteLine(result.Result.Message);

            //Task.Run(async () =>
            //{
            //    await Task.Delay(2000);
            //    while (true)
            //    {
            //        //var result = await modbus.Read<float>(1, 3, 0, 2);
            //        var result = await modbus.Read<ushort>(1, 3, 0, 1);
            //        //var result = await modbus.Read<bool>(1, 1, 0, 4);
            //        if (result.Code == 0)
            //            //resultValues = modbusRTU.Read<float>(1, 3, 0, 2);
            //            result.Datas.ForEach(r => Console.WriteLine(r));
            //        else
            //            Console.WriteLine(result.Message);

            //    }
            //    modbus.Close();
            //});



            ////modbus.WriteCoil(new System.Collections.Generic.List<bool> { false }, 1, 3);
            //var result = modbus.WriteRegister<ushort>(new System.Collections.Generic.List<ushort> { 12, 34 }, 1, 0);
            //if (result.Result.Code == 0)
            //{
            //    Console.WriteLine("写入成功");
            //}
            //else
            //    Console.WriteLine(result.Result.Message);

            Console.ReadKey();
        }
    }
}
